﻿package com.cilico.components;


import java.util.ArrayList;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Typeface;
import android.text.TextPaint;
import android.view.MotionEvent;
import android.widget.TextView;

import com.cilico.ConfigManager;
import com.cilico.R;
import com.cilico.shopcart.ShopCartInfo;
import com.cilico.utils.ConstantRepository;
import com.cilico.utils.Utils;
import com.cilico.view.DetailView;
import com.cilico.view.BaseView;
import com.cilico.view.LoginView;

/**
 * 顶部标题栏
 * 
 * @author lv.xiangan
 *
 */
public class TitleBar extends TextView {

	private static final int LOGO_LEFT_MARGIN = 8;
	private static final int TITLE_LEFT_MARGIN = 10;

	private final Bitmap backButtonNormal_; // 返回（未选）
	private final Bitmap homeButtonNormal_; // 退出（未选）
	private final Bitmap backButtonDown_;   // 返回（点击）
	private final Bitmap homeButtonDown_;   // 退出（点击）
	private Bitmap leftButton_;
	private Bitmap rightButton_;
	private Bitmap scLeftButton_;
	private Bitmap scrightButton_;
	private Bitmap backgroundImg_;
	private Bitmap titleLogo_;
	private String titleAltText_;
	private final TextPaint paint_;
	private int currentType_ = 1;//标记titleBar当前样式
	public int textColor_;
	public int width_;
	public int height_;
	// 是否显示返回图片标志
	public boolean showBack_;
	// 是否显示首页图片(HeaderPicture)标志
	public boolean showHeader_;
	// 暂定按钮与界面的边距为10像素
	private final int imgBlank_ = 10;
	// 字高暂定为16像素
	private final int textSize_ = 16;
	public String backText_ = "";
	// 首页按钮显示字符串
	private final String headerText_;
	// 九宫格界面的退出按钮文字
	private String headerExit_;
	
	public Object object = null;
	BaseView bv_;
	/**
	 * True if the title image is custom and should cover our logo.
	 */
	private long systemTime_=0;
	/**
	 * Creates a new TitleBar object with the given title logo.
	 * 
	 * @param titleLogo
	 *            Logo of the title bar
	 * @throws NullPointerException
	 *             if the title logo is NULL
	 */
	public TitleBar(Context context) {
		super(context);
		bv_ = (BaseView) context;
		paint_ = getPaint();
		paint_.setTypeface(Typeface.DEFAULT_BOLD);
		paint_.setAntiAlias(true);
		textColor_ = Utils.WHITE;
		headerText_ = bv_.getString(R.string.menuExit);
		// create back button.
		backButtonNormal_ = ConstantRepository.decodeBitmap(context.getResources(), R.drawable.back_normal);
		backButtonDown_ = ConstantRepository.decodeBitmap(context.getResources(), R.drawable.back_down);
		// create home button.
		homeButtonNormal_ = ConstantRepository.decodeBitmap(context.getResources(), R.drawable.home_normal);
		homeButtonDown_ = ConstantRepository.decodeBitmap(context.getResources(), R.drawable.home_down);
		
		leftButton_ = backButtonNormal_;
		rightButton_ = homeButtonNormal_;
		
		getBackgroundImg(R.drawable.t_bar);
		
		height_ = backgroundImg_.getHeight(); 
		setFocusable(false);
		setFocusableInTouchMode(false);
	}

	private void getBackgroundImg (int imgId) {
		// create background image.
		backgroundImg_ = ConstantRepository.decodeBitmap(bv_.getResources(), imgId);
		// 根据手机屏宽度适当对背景图进行缩放
		if (backgroundImg_.getWidth() > 0 && backgroundImg_.getHeight() > 0 && Utils.screenWidth_ != backgroundImg_.getWidth() && Utils.screenWidth_ > 0) {
			backgroundImg_ = Bitmap.createScaledBitmap(backgroundImg_, Utils.screenWidth_, backgroundImg_.getHeight()
					* Utils.screenWidth_ / backgroundImg_.getWidth(), true);
		}
	}
	
	
	/**
	 * @param type int 标记titleBar的样式
	 * @param title String titleBar的标题
	 * @param leftButton String 返回按钮
	 * @param rightButton String 右边的按钮
	 * */
	public void resetTitleBarContent(int type, String title, String leftButton, String rightButton) {
		if(currentType_ == 1 && type == 1) return;//如果当前和需要切换的样式一样，则不执行下面的操作 
		
		switch(type) {
		case 1://手机银行原有模式
			if(backgroundImg_ != null) {
				backgroundImg_.recycle();
				backgroundImg_ = null;
			}
			getBackgroundImg(R.drawable.t_bar);
			setTitleAltText(title);
			break;
		}
		currentType_ = type;
		invalidate();
	}

	private void paintContent(Canvas g) {
		paint_.setFakeBoldText(false);
		paint_.setTextSize(Utils.getScaledValue(ConfigManager.SIZE_MEDIUM));
		
		if (titleAltText_ != null) {
			paint_.setColor(textColor_);
			float x = (Utils.screenWidth_ - paint_.measureText(titleAltText_)) / 2;
			float y = (45 + paint_.getTextSize()) / 2;
			if (titleAltText_.length()>7){
				g.drawText(titleAltText_.substring(0, 6).concat("...").toString(), (Utils.screenWidth_ - paint_.measureText(titleAltText_.substring(0, 6).concat("...").toString())) / 2, y, paint_);
			} else{
				g.drawText(titleAltText_, x, y, paint_);
			}
		}

	}


	/**
	 * Set the alternate text of the title image.
	 * 
	 * @param titleAltText
	 *            the text that may be used in place of the image
	 */
	public void setTitleAltText(String titleAltText) {
		titleAltText_ = titleAltText;
		resetTitleAltText();
	}

	String getTitleAltText() {
		return titleAltText_;
	}

	/**
	 * Reset the alternate text of the title image.
	 */
	private void resetTitleAltText() {
		/*
		 * If we have enough space, paint Title text in medium font, else we paint it in small font, now if we still
		 * don’t have enough space, then we paint the abbreviation of Title text.
		 */
		paint_.setTypeface(Typeface.DEFAULT_BOLD);
		paint_.setTextSize(Utils.getScaledValue(ConfigManager.SIZE_MEDIUM));
		if (width_ <= 0 || titleAltText_ == null) {
			return;
		}
		int usedWidth = LOGO_LEFT_MARGIN + TITLE_LEFT_MARGIN;
		if (titleLogo_ != null)
			usedWidth += titleLogo_.getWidth();
		if (usedWidth > width_ - (paint_.measureText(titleAltText_))) {
			titleAltText_ = Utils.abbrevString(titleAltText_, paint_, width_ - usedWidth);
		}
	}

	public void setWidth(int width) {
		width_ = width;
		resetTitleAltText();
	}

	public boolean onTouchEvent(MotionEvent me) {
		int action = me.getAction();
		int x = (int) me.getX();
		switch (action) {
		case MotionEvent.ACTION_DOWN:
			if (x <= (this.imgBlank_ + this.backButtonNormal_.getWidth())) {
				// 用户点击了“返回”或者“退出”
				leftButton_ = backButtonDown_;
			} else if (x >= (width_ - this.imgBlank_ - homeButtonNormal_.getWidth())) {
				// 用户点击了“返回首页”
				if (BaseView.mid_.poiRepo_.getActionSize() > 0) {
					// 判断压栈的poi个数，当栈中无元素时，表示还未显示一个可用页面，此时点击“首页”按钮不改变其显示效果
					rightButton_ = homeButtonDown_;
				}
			}
			invalidate();
			break;
		case MotionEvent.ACTION_UP:
			systemTime_=System.currentTimeMillis()-systemTime_;
			if (x <= (imgBlank_ + backButtonNormal_.getWidth())) {
				// 用户点击了“返回”
				
				if (showBack_) {
					leftButton_ = backButtonNormal_;
					invalidate();
					if (systemTime_ < 1000) {	
						return true;
					}
					if (bv_ instanceof LoginView) {
						LoginView loginView = (LoginView)bv_;
						loginView.isExit = false;
					}
					bv_.keyBackPressed();
				}
			} else if (showHeader_) {
				if (x >= (width_ - this.imgBlank_ - homeButtonNormal_.getWidth())) {
					// 用户点击了“退出”
					Alert.exitSystem(bv_);
					
				}
			}
			super.onTouchEvent(me);
			break;
		default:
			super.onTouchEvent(me);
			break;

		}
		return true;
	}

	public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		setMeasuredDimension(width_, height_);
	}

	public void onDraw(Canvas g) {
		/* clear title bar. */
		// g.drawColor(bgColor_);
		// paint_.setStyle(Paint.Style.FILL);
		// g.drawRect(0, 0, width_, height_, paint_);
		if (backgroundImg_ != null) {
			g.drawBitmap(backgroundImg_, 0, 0, paint_);
		}
		/* paint logo. */
		// paintLogo(g);
		paintButton(g);
		/* paint contents. */
		 paintContent(g);
	}

	private void paintButton(Canvas g) {
		// TODO Auto-generated method stub
		paint_.setTextSize(Utils.getScaledValue(textSize_));
		paint_.setColor(textColor_);
		paint_.setFakeBoldText(false);
		int width;
		
		/* 绘制返回 */
		if (this.showBack_) {
			if (currentType_ == 2){
				if(scLeftButton_ == null) {
					scLeftButton_ = ConstantRepository.decodeBitmap(bv_.getResources(), R.drawable.back);
				}
				g.drawBitmap(scLeftButton_, imgBlank_, ((height_ - scLeftButton_.getHeight()) >> 1) + 1, paint_);
			} else{
				width = (int) paint_.measureText(this.backText_);
				g.drawBitmap(leftButton_, this.imgBlank_, ((height_ - leftButton_.getHeight()) >> 1) + 1, paint_);
				float x = (leftButton_.getWidth() * 1.1f - width) / 2 + imgBlank_;
				float y = Utils.getUserDeviceScaledValue((height_ + textSize_ * 0.8f) / 2);
				g.drawText(this.backText_, x, y, paint_);	
			}
		}

		/* 绘制退出 */
		if (this.showHeader_) {
			if (currentType_ == 2){
				if(scrightButton_ == null) {
					scrightButton_ = ConstantRepository.decodeBitmap(bv_.getResources(), R.drawable.home);
				}
				g.drawBitmap(scrightButton_, width_ - imgBlank_ - scrightButton_.getWidth(), ((height_ - scrightButton_.getHeight()) >> 1) + 1, paint_);
			} else {
				if (null != this.headerExit_)
					width = (int) paint_.measureText(this.headerExit_);
				else
					width = (int) paint_.measureText(this.headerText_);
				g.drawBitmap(rightButton_, width_ - imgBlank_ - rightButton_.getWidth(), ((height_ - rightButton_.getHeight()) >> 1) + 1, paint_);
				float x = width_ - imgBlank_ - rightButton_.getWidth() + ((rightButton_.getWidth() - width) >> 1);
				float y = Utils.getUserDeviceScaledValue((height_ + textSize_ * 0.8f) / 2);
				if (null != this.headerExit_)
					g.drawText(this.headerExit_, x, y, paint_);
				else
					g.drawText(this.headerText_, x, y, paint_);
			}
		}
	}

	public void setHpText(String string) {
		// TODO Auto-generated method stub
		headerExit_ = string;
	}
	
	public void setCartButton () {
		
	}
}
